package com.itheima.provider.controller;

import com.itheima.provider.domain.Goods;
import com.itheima.provider.service.GoodsService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Goods Controller 服务提供方
 */

@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    @Value("${server.port}")
    private int port;

    @GetMapping("/findOne/{id}")
    // 注解配置降级方法
    @HystrixCommand(fallbackMethod = "findOne_fallback",commandProperties = {
            // 设置属性值，不适用默认的一秒超时时间，设为3秒
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000"),
            // 监控时间5000毫秒
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "5000"),
            // 失败次数，默认20次
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),
            // 失败率，默认50(百分比)
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "50")
    })
    public Goods findOne(@PathVariable("id") int id){

        Goods goods = goodsService.findOne(id);

        // int i = 1/0;
        // 如果id == 1,则出现异常，id!= 1则正常访问
        if(id == 1){
            int i = 1 / 0;
        }

        /*try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/

        goods.setTitle(goods.getTitle() + ":" + port);//将端口号，设置到了 商品标题上
        return goods;
    }

    /**
     *  定义降级方法：
     *  1. 方法返回值和原方法一致
     *  2. 方法参数和原方法一致
     *  即只有方法名不同
     */
    public Goods findOne_fallback(int id){
        Goods goods = new Goods();
        goods.setTitle("服务提供方降级了。。。");

        return goods;
    }
}
